package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.FileUtils;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Controller
@Scope("prototype")
@Namespace("/")//<package namespace extends
@ParentPackage("struts-default")
@Results({@Result(name="list",type="redirect",location="/pages/base/area.jsp")})
public class AreaAction extends BaseAction<Area> {

	/*private Area model=new Area();
	public Area getModel() {
		// TODO Auto-generated method stub
		return model;
	}*/
	
	@Autowired
	private AreaService areaService;
	
	//定义变量接收上传文件
	private File upload;
	//接收文件MIME类型，文件名称
	private String uploadContentType;
	private String uploadFileName;
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}


	/**
	  * @Description: 通过POI解析excel文件中数据
	 */
	@Action("areaAction_importXls")
	public String importXls() throws Exception {
		List<Area> list=new ArrayList<>();
		//创建excel文件对象
		HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(upload));
		//获取标签页(Sheet1,Sheet2,Sheet3)
		HSSFSheet sheet = workbook.getSheetAt(0);
		//遍历标签页获取行
		for (Row row : sheet) {
			//忽略标题行
			if(row.getRowNum()==0){
				continue;
			}
			String id=row.getCell(0).getStringCellValue();
			String province = row.getCell(1).getStringCellValue();
			String city  = row.getCell(2).getStringCellValue();
			String district = row.getCell(3).getStringCellValue();
			String postcode = row.getCell(4).getStringCellValue();
			//创建区域对象
			Area area=new Area(id, province, city, district, postcode, null, null);
			
			//将省市区（县）截取掉
			province = province.substring(0,province.length()-1);
			city = city.substring(0,city.length()-1);
			district = district.substring(0,district.length()-1);
			
			String all=province+city+district;
			//简码：HBSJZQD
			String[] strings = PinYin4jUtils.getHeadByString(all);
			String shortcode = StringUtils.join(strings);
			area.setShortcode(shortcode);
			
			//城市编码：shijiazhuang
			String citycode = PinYin4jUtils.hanziToPinyin(city,"");
			System.out.println(citycode);
			area.setCitycode(citycode);
			
			list.add(area);
		}
		areaService.save(list);
		
		//释放资源
		workbook.close();
		//由于提交表单到Iframe中，故配置结果视图也看不到
		return NONE;
	}
	
	
	
	/**
	 * 区域分页查询
	 * @return
	 * @throws Exception
	 */
	@Action("areaAction_pageQuery")
	public String pageQuery() throws Exception {
		Pageable pageable=new PageRequest(page-1, rows);
		Page<Area> page=areaService.pageQuery(pageable);
		this.java2Json(page, new String[]{"subareas"});
		return NONE;
	}
	
	/**
	  * @Description: 查询所有区域记录
	  * @return json数组
	  * @throws Exception
	  *	  
	 */
	@Action("areaAction_findAll")
	public String findAll() throws Exception {
		List<Area> list=areaService.findAll();
		this.java2Json(list, new String[]{"subareas"});
		return NONE;
	}
	
	@Autowired
	private DataSource dataSource;
	
	/**
	  * @Description: 通过jasperReport解析编译jrxml模板文件，生成PDF文件，将文件下载
	 */
	@Action("areaAction_exportPDF")
	public String execute() throws Exception {
		// 读取 jrxml 文件 ,根据相对路径获取绝对路径（文件磁盘路径）
		String jrxml = ServletActionContext.getServletContext().getRealPath("/jasperreport/area.jrxml");
		// 准备需要数据
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("company", "传智播客");
		parameters.put("createDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		// 准备需要数据（compile编译jrxml文件）
		JasperReport report = JasperCompileManager.compileReport(jrxml);
		JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, dataSource.getConnection());

		HttpServletResponse response = ServletActionContext.getResponse();
		OutputStream ouputStream = response.getOutputStream();
		// 设置相应参数，以附件形式保存PDF
		response.setContentType("application/pdf");  //去Servers下web.xml搜索pdf
		response.setCharacterEncoding("UTF-8");
		//作为附件去下载     filename指定文件名称   FileUtils处理中文名称乱码问题     user-agent获取是哪种浏览器
		response.setHeader("Content-Disposition", "attachment; filename=" + FileUtils.encodeDownloadFilename("区域数据.pdf",
		ServletActionContext.getRequest().getHeader("user-agent")));
		// 使用JRPdfExproter导出器导出pdf
		JRPdfExporter exporter = new JRPdfExporter();
		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
		exporter.exportReport();// 导出
		ouputStream.close();// 关闭流		
		return NONE;
	}
	@Action("areaAction_addArea")
	public String addArea() throws Exception {
		String province= model.getProvince();
		String city =model.getCity();
		String district =model.getDistrict();
		Area area= areaService.findByProvinceAndCityAndDistrict(province,city,district);
		Map<String, String> map =new HashMap();
		if (area==null) {
			//将省市区（县）截取掉
			province = province.substring(0,province.length()-1);
			city = city.substring(0,city.length()-1);
			district = district.substring(0,district.length()-1);
			
			String all=province+city+district;
			//简码：HBSJZQD
			String[] strings = PinYin4jUtils.getHeadByString(all);
			String shortcode = StringUtils.join(strings);
			model.setShortcode(shortcode);
			
			//城市编码：shijiazhuang
			String citycode = PinYin4jUtils.hanziToPinyin(city,"");
			System.out.println(citycode);
			model.setCitycode(citycode);
			String id = UUID.randomUUID().toString();
			model.setId(id);
			areaService.addArea(model);
			map.put("msg", "保存成功!!");
		}else{
			map.put("msg", "已存在,请勿重复添加!!");			
		}
		 String data= net.sf.json.JSONObject.fromObject(map).toString();
		 System.out.println(data);
		 ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		 ServletActionContext.getResponse().getWriter().write(data);
		return NONE;
	}

}
